package diploma.kisel.modelas.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import diploma.kisel.hibernate.util.HibernateUtil;
import diploma.kisel.modelas.domain.Computer;
import diploma.kisel.modelas.domain.Program;
import diploma.kisel.modelas.domain.ProgramType;
import diploma.kisel.modelas.repository.api.ProgramRepository;

public class ProgramRepositoryImpl implements ProgramRepository{
	
	private EntityManager em = HibernateUtil.getEm();

	@Override
	public List<Program> findAll() {
		List<Program> programs= em.createNamedQuery(
				"Program.findAll", Program.class).getResultList();		
		return programs;
	}

	@Override
	public Program findByid(int id) {
		TypedQuery<Program> query = em.createNamedQuery("Program.findById", Program.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	@Override
	public Program save(Program program) {
		em.getTransaction().begin();
		em.persist(program);
		em.getTransaction().commit();
		return program;
	}

	@Override
	public Program update(Program program) {
		em.getTransaction().begin();
		em.merge(program);
		em.getTransaction().commit();
		return program;
	}

	@Override
	public void remove(Program program) {
		em.getTransaction().begin();
		Program mergedProgram = em.merge(program);
		em.remove(mergedProgram);			
		em.getTransaction().commit();		
	}

	@Override
	public List<Program> findByPrice(int minPrice, int maxPrice) {
		TypedQuery<Program> query = em.createNamedQuery(
				"Program.findByPrice", Program.class);
		query.setParameter("minPrice", minPrice);
		query.setParameter("maxPrice", maxPrice);
		return query.getResultList();
	}

	@Override
	public List<Program> findByPriceAndType(int minPrice, int maxPrice,
			ProgramType type) {
		TypedQuery<Program> query = em.createNamedQuery(
				"Program.findByPriceAndType", Program.class);
		query.setParameter("minPrice", minPrice);
		query.setParameter("maxPrice", maxPrice);
		query.setParameter("type", type);
		return query.getResultList();
	}

}
